import React, { useState, useEffect } from 'react'
import './style/Cang.css'
import axios from 'axios';
import { Empty, Uploader, Toast, Dialog } from 'react-vant';
import { Popup, Space, Button, Form, Input } from 'react-vant';
import { useNavigate } from 'react-router-dom'
import { ArrowLeft, AddO, Edit, Delete } from '@react-vant/icons';

interface Collection {
  _id: string;
  name: string;
  img: string;
}

export default function Cang() {
  const navigate = useNavigate()
  const [visible4, setVisible4] = useState(false)
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState('');
  const [form] = Form.useForm();
  const [list, setList] = useState<Collection[]>([]);
  const [editingCollection, setEditingCollection] = useState<Collection | null>(null);

  const handleUploadChange = async (file: File) => {
    if (!file) return;
    
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
      Toast.fail('只支持 JPG、PNG、GIF 格式的图片');
      return;
    }

    const maxSize = 5 * 1024 * 1024;
    if (file.size > maxSize) {
      Toast.fail('图片大小不能超过5MB');
      return;
    }

    setUploading(true);
    setUploadError('');

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await axios.post('http://localhost:3000/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        transformRequest: [(data) => data] // 防止 axios 自动转换 FormData
      });

      if (response.data.code === 200) {
        form.setFieldValue('img', response.data.url);
        Toast.success('上传成功');
      } else {
        throw new Error(response.data.message || '上传失败');
      }
    } catch (error: any) {
      console.error('文件上传失败', error);
      if (error.response) {
        // 服务器返回了错误响应
        Toast.fail(error.response.data?.message || '上传失败，请重试');
      } else if (error.request) {
        // 请求发送了但没有收到响应
        Toast.fail('网络错误，请检查网络连接');
      } else {
        // 请求配置出错
        Toast.fail('上传失败，请重试');
      }
    } finally {
      setUploading(false);
    }
  };

  const getlist = async () => {
    try {
      const res = await axios.get(`http://localhost:3000/list`);
      setList(res.data.list);
    } catch (error) {
      Toast.fail('获取收藏列表失败');
    }
  };

  useEffect(() => {
    getlist();
  }, []);

  const handleSubmit = async () => {
    try {
      const values = await form.getFieldsValue();
      console.log('表单数据:', values);
      
      if (!values.img) {
        alert('请先上传封面图片');
        return;
      }

      if (!values.name) {
        alert('请输入收藏夹标题');
        return;
      }

      if (editingCollection) {
        await axios.put(`http://localhost:3000/list/${editingCollection._id}`, values);
        alert('更新成功');
      } else {
        await axios.post('http://localhost:3000/add', values);
        alert('创建成功');
      }
      setVisible4(false);
      form.resetFields();
      setEditingCollection(null);
      getlist();
    } catch (error) {
      console.error('操作失败:', error);
      alert('操作失败');
    }
  };

  const handleDelete = async (_id: string) => {
    Dialog.confirm({
      title: '确认删除',
      message: '确定要删除这个收藏夹吗？',
    }).then(async () => {
      try {
        await axios.delete(`http://localhost:3000/del`, {
          data: { _id } // 将参数放在请求体中
        });
        Toast.success('删除成功');
        getlist();
      } catch (error) {
        Toast.fail('删除失败');
      }
    });
  };

  const handleEdit = (collection: Collection) => {
    setEditingCollection(collection);
    form.setFieldsValue(collection);
    setVisible4(true);
  };

  return (
    <div className="collection-page">
      <div className='navigator'>
        <ArrowLeft onClick={() => navigate('/detailCar')} />
        <h2>我的收藏</h2>
        <AddO onClick={() => {
          setEditingCollection(null);
          form.resetFields();
          setVisible4(true);
        }} />
      </div>

      <div className="main">
        {list.length === 0 ? (
          <Empty description="暂无收藏" />
        ) : (
          <div className="collection-grid">
            {list.map((item) => (
              <div key={item._id} className='collection-item'>
                <div className="collection-image" onClick={() => navigate('/detailshow', { state: item })}>
                  <img src={item.img} alt={item.name} />
                </div>
                <div className="collection-info">
                  <span className="collection-name">{item.name}</span>
                  <div className="collection-actions">
                    <Edit onClick={() => handleEdit(item)} />
                    <Delete onClick={() => handleDelete(item._id)} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <Popup
        visible={visible4}
        onClose={() => {
          setVisible4(false);
          form.resetFields();
          setEditingCollection(null);
        }}
        position='right'
        bodyStyle={{ width: '80vw', padding: '20px' }}
      >
        <Form
          form={form}
          footer={
            <div style={{ marginTop: '20px' }}>
              <Button type="primary" block onClick={handleSubmit}>
                {editingCollection ? '更新' : '创建'}
              </Button>
            </div>
          }
        >
          <Form.Item
            name="img"
            label="封面"
            rules={[{ required: true, message: '请上传封面图片' }]}
          >
            <Uploader
              accept="image/*"
              maxCount={1}
              onChange={(files) => {
                if (files[0]?.file) {
                  handleUploadChange(files[0].file);
                }
              }}
            />
          </Form.Item>
          <Form.Item
            name="name"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入收藏夹标题" />
          </Form.Item>
        </Form>
      </Popup>
    </div>
  );
}
